﻿using System;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Routing;
    
namespace Gama.Extension
{
    public static partial class HtmlHelperExtensions
    {
        public static ActionImageLinkBuilder<TController> ActionImageLinkEx<TController>(this HtmlHelper htmlHelper, Expression<Func<TController, ActionResult>> expression, string source)
            where TController : Controller
        {
            return new ActionImageLinkBuilder<TController>(htmlHelper, expression, source);
        }
    }

    public class ActionImageLinkBuilder<TController> : HtmlElementBuilder
        where TController : Controller
    {
        private Expression<Func<TController, ActionResult>> expression;
        private string alternateText;
        private string source;

        internal ActionImageLinkBuilder(HtmlHelper htmlHelper, Expression<Func<TController, ActionResult>> expression, string source)
            : base(htmlHelper)
        {
            this.expression = expression;
            this.source = source;
        }

        public override string Build()
        {
            var body = this.expression.Body as MethodCallExpression;

            Debug.Assert(body != null); 

            // generate routes
            RouteValueDictionary routes = ControllerExtensions.CreateRoutes<TController>(body);

            // prepare url generator
            UrlHelper urlHelper = new UrlHelper(this.htmlHelper.ViewContext.RequestContext);

            // create html element
            TagBuilder anchor = new TagBuilder("a");
            TagBuilder image = new TagBuilder("img");

            image.MergeAttribute("src", this.source);
            image.MergeAttribute("alt", this.alternateText);
            anchor.MergeAttributes(new RouteValueDictionary(this.htmlAttributes));
            anchor.MergeAttribute("href", urlHelper.Action(routes["action"].ToString(), routes["controller"].ToString(), routes));
            anchor.InnerHtml = image.ToString();
            
            return anchor.ToString();
        }

        public ActionImageLinkBuilder<TController> AlternateText(string alternateText)
        {
            this.alternateText = alternateText;

            return this;
        }
    }    
}
